import { defineStore } from 'pinia'
import { ref } from 'vue'

export type QuestionType = 'radio' | 'checkbox' | 'text'

export interface Question {
    id: string
    type: QuestionType
    title: string
    options?: string[]
    required?: boolean
}

export interface Survey {
    id: string
    title: string
    description?: string
    endTime?: string
    questions: Question[]
    submissions: Record<string, any>[]
}

export const useSurveyStore = defineStore('survey', () => {
    const surveys = ref<Survey[]>([])
    const currentSurvey = ref<Survey | null>(null)

    // 从本地存储加载数据
    const loadSurveys = () => {
        const saved = localStorage.getItem('surveys')
        if (saved) surveys.value = JSON.parse(saved)
    }

    // 保存到本地存储
    const saveSurveys = () => {
        localStorage.setItem('surveys', JSON.stringify(surveys.value))
    }

    // 创建新问卷
    const createSurvey = (title: string) => {
        const newSurvey: Survey = {
            id: Date.now().toString(),
            title,
            questions: [],
            submissions: []
        }
        surveys.value.push(newSurvey)
        currentSurvey.value = newSurvey
        saveSurveys()
        return newSurvey.id
    }

    // 添加问题
    const addQuestion = (type: QuestionType) => {
        if (!currentSurvey.value) return

        const newQuestion: Question = {
            id: Date.now().toString(),
            type,
            title: '新问题',
            required: false
        }

        if (type !== 'text') {
            newQuestion.options = ['选项1', '选项2']
        }

        currentSurvey.value.questions.push(newQuestion)
        saveSurveys()
    }

    // 删除问题
    const removeQuestion = (questionId: string) => {
        if (!currentSurvey.value) return

        currentSurvey.value.questions = currentSurvey.value.questions.filter(
            q => q.id !== questionId
        )
        saveSurveys()
    }

    // 提交问卷
    const submitSurvey = (answers: Record<string, any>) => {
        if (!currentSurvey.value) return

        currentSurvey.value.submissions.push(answers)
        saveSurveys()
    }

    // 初始化
    loadSurveys()

    return {
        surveys,
        currentSurvey,
        createSurvey,
        addQuestion,
        removeQuestion,
        submitSurvey,
        saveSurveys
    }
})
